package com.apotik.legenda.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;

import com.apotik.legenda.custom.TableModelCustom;
import com.apotik.legenda.dao.ProductDao;
import com.apotik.legenda.model.Product;
import com.apotik.legenda.observer.PosObserver;
import com.apotik.legenda.util.AppUtil;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;

public class AddProductToTrxDialog extends JDialog implements ActionListener, KeyListener {
	private static final long serialVersionUID = 1L;
	
	private JTextField textFieldCari;
	private TableModelCustom tableModel;
	private JTable table;
	private JLabel lblSelectedvalue;
	private JLabel lblQuantityVal;
	
	private JButton btnSubmit;
	private JButton btnClear;
	
	private PosObserver observer;
	private int modelRow  = -1;
	private Product productSelected = null;
	private int quantityInput = 0;
	
	public AddProductToTrxDialog(PosObserver observer) {
		this.observer = observer;
		
		int heightFrame = 350;
		
		setTitle("Add Stock");
		setSize(900, heightFrame);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		addKeyListener(this);
		
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(190, dim.height-heightFrame-100);
		
		JPanel panelNorth = panelNorth();
		getContentPane().add(panelNorth, BorderLayout.NORTH);
		
		JScrollPane scrollPane = panelCenter();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		JPanel panelSouth = panelSouth();
		getContentPane().add(panelSouth, BorderLayout.SOUTH);
	}
	
	private JPanel panelNorth(){
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 0, 5, 0));
		panel.setLayout(new BorderLayout());
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.WEST);
		
		JLabel lblCari = new JLabel("Cari:  ");
		lblCari.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_1.add(lblCari);
		
		textFieldCari = new JTextField();
		textFieldCari.addKeyListener(this);
		textFieldCari.setFont(new Font("Tahoma", Font.PLAIN, 13));
		textFieldCari.setHorizontalAlignment(SwingConstants.LEFT);
		panel_1.add(textFieldCari);
		textFieldCari.setColumns(20);
		
		
		
		return panel;
	}
	
	@SuppressWarnings("serial")
	private JScrollPane panelCenter(){
		JScrollPane scrollPane = new JScrollPane();
		
		String[] columnNames = {"Kode Barang", "Nama Barang", "Harga", "Tersedia"};
		tableModel = new TableModelCustom(columnNames);
		
		table = new JTable(){
			@Override
			public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
				JLabel label = (JLabel) super.prepareRenderer(renderer, row, column);
				if(column==2 || column==3){
					label.setHorizontalAlignment(JLabel.RIGHT);
				}else{
					label.setHorizontalAlignment(JLabel.LEFT);
				}
				return label;
				//return super.prepareRenderer(renderer, row, column);
			}
		};
		table.setModel(tableModel);
		table.setEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@SuppressWarnings("rawtypes")
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table.getSelectedRow();
				if(viewRow>-1){
					modelRow = table.convertRowIndexToModel(viewRow);
					
					Vector v = (Vector) tableModel.getRowVector().get(modelRow);
					if(v!=null){
						productSelected = (Product) v.get(v.size()-1);
						lblSelectedvalue.setText(productSelected.getProductCode()+" - "+productSelected.getProductName());
					}
					
				}
			}
		});
		scrollPane.setViewportView(table);
		
		String actionMapKeySpace = "key_space";
		table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), actionMapKeySpace);
		table.getActionMap().put(actionMapKeySpace, new AbstractAction() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//System.out.println("ProductName: "+productSelected.getProductName());
				
				if(productSelected.getPriceSell().intValue()<1){
					JOptionPane.showMessageDialog(null, "Silahkan pilih item lain. Harga Satuan Rp 0. Tidak bisa dilanjutkan", "Message", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				if(productSelected.getAvailableStock()<1){
					JOptionPane.showMessageDialog(null, "Silahkan pilih item lain, Stok saat ini sedang habis", "Message", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				JTextField textFieldQuantity = new JTextField();
				textFieldQuantity.setText(Integer.toString(quantityInput));
				final JComponent[] inputs = new JComponent[] {
						new JLabel("Quantity"), textFieldQuantity,
						
				};
				JOptionPane.showMessageDialog(null, inputs, "Input Kuantitas", JOptionPane.PLAIN_MESSAGE);
				//System.out.println("Quantity: "+textFieldQuantity.getText().trim());
				
				String quantityStr = textFieldQuantity.getText().trim();
				
				if(quantityStr.equalsIgnoreCase("")){
					JOptionPane.showMessageDialog(null, "Silahkan isi kuantitas", "Message", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				if(!AppUtil.isNumber(quantityStr)){
					JOptionPane.showMessageDialog(null, "Kuantitas yang Anda masukkan bukan angka", "Message", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				int quantityInt = Integer.parseInt(quantityStr);
				if(productSelected.getAvailableStock()<quantityInt){
					JOptionPane.showMessageDialog(null, "Kuantitas yang Anda masukkan melebihi dari stok yang tersedia", "Message", JOptionPane.ERROR_MESSAGE);
					return;
				}

				quantityInput = quantityInt;
				lblQuantityVal.setText(Integer.toString(quantityInt));
			}
		});
		
		return scrollPane;
	}

	private JPanel panelSouth(){
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(null);
		
		JLabel lblSelected = new JLabel("Selected");
		lblSelected.setBounds(5, 2, 80, 23);
		lblSelected.setHorizontalAlignment(SwingConstants.LEFT);
		lblSelected.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(lblSelected);
		
		JLabel labelTd1 = new JLabel(":");
		labelTd1.setBounds(67, 2, 21, 23);
		labelTd1.setHorizontalAlignment(SwingConstants.RIGHT);
		labelTd1.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(labelTd1);
		
		lblSelectedvalue = new JLabel("-");
		lblSelectedvalue.setBounds(98, 2, 300, 20);
		lblSelectedvalue.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_1.add(lblSelectedvalue);
		
		JLabel lblQuantity = new JLabel("Quantity");
		lblQuantity.setBounds(5, 24, 68, 23);
		lblQuantity.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(lblQuantity);
		
		JLabel labelTd2 = new JLabel(":");
		labelTd2.setBounds(67, 24, 21, 23);
		labelTd2.setHorizontalAlignment(SwingConstants.RIGHT);
		labelTd2.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panel_1.add(labelTd2);
		
		lblQuantityVal = new JLabel("-");
		lblQuantityVal.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblQuantityVal.setBounds(95, 24, 74, 23);
		panel_1.add(lblQuantityVal);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(13, 0, 13, 9));
		panel.add(panel_2, BorderLayout.EAST);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		btnSubmit = new JButton("Submit");
		btnSubmit.addActionListener(this);
		btnSubmit.addKeyListener(this);
		btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(btnSubmit, BorderLayout.WEST);
		
		JLabel lblSpaceBtn = new JLabel(" ");
		panel_2.add(lblSpaceBtn, BorderLayout.CENTER);
		
		btnClear = new JButton("Clear");
		btnClear.addActionListener(this);
		btnClear.addKeyListener(this);
		btnClear.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel_2.add(btnClear, BorderLayout.EAST);
		
		
		return panel;
	}
	
	private void clearData(){
		textFieldCari.setText("");
		tableModel.removeRowAll();
		modelRow = -1;
		productSelected = null;
		quantityInput = 0;
		lblSelectedvalue.setText("-");
		lblQuantityVal.setText("-");
		textFieldCari.requestFocus();
	}
	
	private void closeDialog(){
		this.setVisible(false);
	}
	
	private void btnSubmitAction(){
		if(productSelected==null){
			JOptionPane.showMessageDialog(null, "Tidak ada item yang dipilih", "Message", JOptionPane.ERROR_MESSAGE);
			table.requestFocus();
		}else{
			if(quantityInput==0){
				JOptionPane.showMessageDialog(null, "Kuantitas harus lebih dari 0", "Message", JOptionPane.ERROR_MESSAGE);
				table.requestFocus();
				return;
			}
			
			observer.insertProduct(productSelected, quantityInput);
			clearData();
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		
		if(obj==btnSubmit){
			btnSubmitAction();
		}else if(obj==btnClear){
			clearData();	
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void keyPressed(KeyEvent ke) {
		if(ke.getKeyCode()==KeyEvent.VK_ESCAPE){
			closeDialog();
		}
		
		Object obj = ke.getSource();
		
		if(obj==textFieldCari){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				String param = textFieldCari.getText().trim();
				if(param.trim().equalsIgnoreCase("")){
					tableModel.removeRowAll();
				}else{
					ProductDao dao = new ProductDao();
					List<Product> list = dao.listByCodeOrName(param);
					tableModel.removeRowAll();
					if(list.size()>0){
						for(Product product: list){
							String harga = "0";
							if(product.getPriceSell()!=null){
								harga = AppUtil.formatStringIDR(product.getPriceSell().intValue());
							}
							
							Vector v = new Vector();
							v.add(product.getProductCode());
							v.add(product.getProductName());
							v.add(harga);
							v.add(product.getAvailableStock()!=null ? product.getAvailableStock().intValue():0);
							v.add(product);
							tableModel.insertData(v);
						}
					}else{
						JOptionPane.showMessageDialog(null, param+" not found", "Exception", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		}else if(obj==btnSubmit){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				btnSubmitAction();
			}
		}else if(obj==btnClear){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				clearData();
			}
		}
		
	}

	@Override
	public void keyReleased(KeyEvent ke) {
		//Object obj = ke.getSource();
	}

	@Override
	public void keyTyped(KeyEvent ke) {
		// TODO Auto-generated method stub	
	}
}